package com.nebula.service.impl;

import com.nebula.entity.Common;
import com.nebula.entity.Navigation;
import com.nebula.entity.RoleNavigation;
import com.nebula.common.Const;
import com.nebula.dao.ICommonDao;
import com.nebula.dao.INavigationDao;
import com.nebula.dao.impl.CommonDaoImpl;
import com.nebula.dao.impl.NavigationDaoImpl;
import com.nebula.service.IPageSettingService;

import java.util.ArrayList;
import java.util.List;

/**
 * @author CcccX
 * @create 2019-01-15 13:49
 */
public class PageSettingServiceImpl implements IPageSettingService {
    private ICommonDao iCommonDao = new CommonDaoImpl();
    private INavigationDao iNavigationDao = new NavigationDaoImpl();

    @Override
    public int selectRootSort() {
        Common common = iCommonDao.findById(Const.ROOT_SORT_ID);
        return Integer.parseInt(common.getDef());
    }

    @Override
    public int selectChildSort() {
        Common common = iCommonDao.findById(Const.CHILDREN_SORT_ID);
        return Integer.parseInt(common.getDef());
    }

    @Override
    public void add(Navigation navigation, String sortId, String sort, String roleId, String navId) {
        //新增页面
        iNavigationDao.save(navigation);

        //更新排序值
        Common common = new Common();
        common.setId(sortId);
        common.setDef(String.valueOf(Integer.parseInt(sort) + 1));
        iCommonDao.update(common);

        //建立多对多关系
        List<RoleNavigation> roleNavigations = new ArrayList<>();
        String[] roleIDs = roleId.split(",");
        for (String id : roleIDs) {
            RoleNavigation roleNavigation = new RoleNavigation();
            roleNavigation.setRoleId(Integer.parseInt(id));
            roleNavigation.setNavId(navId);
            roleNavigations.add(roleNavigation);
        }
        iNavigationDao.insertRoleNavigation(roleNavigations);
    }

    @Override
    public void update(Navigation navigation, String roleId) {
        //更新导航表
        iNavigationDao.update(navigation);

        //更新中间表 role_navigation
        int resultCount = iNavigationDao.deleteRoleNavigationByNavId(navigation.getId());

        if (resultCount > 0) {
            List<RoleNavigation> roleNavigations = new ArrayList<>();
            String[] roleIDs = roleId.split(",");
            for (String id : roleIDs) {
                RoleNavigation roleNavigation = new RoleNavigation();
                roleNavigation.setRoleId(Integer.parseInt(id));
                roleNavigation.setNavId(navigation.getId());
                roleNavigations.add(roleNavigation);
            }
            iNavigationDao.insertRoleNavigation(roleNavigations);
        }
    }

    @Override
    public void deleteNavigationByNavId(String id) {
        iNavigationDao.delete(id);
    }
}
